package cn.kgc.ssm.controller;

import cn.kgc.ssm.dto.QueryTemplate;
import cn.kgc.ssm.service.TemplateService;
import cn.kgc.ssm.util.ResponseResult;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author 课工场
 * @date 2023/10/26
 * @description 模版的上传下载
 */
@Controller
@RequestMapping("template")
public class TemplateController {

    @Resource
    private TemplateService templateService;

    //资源下载列表信息
    @GetMapping("list")
    @ResponseBody
    public ResponseResult templatePage(QueryTemplate queryTemplate) {

        return templateService.getPageDate(queryTemplate);
    }


    // 文件上传的接口
    @PostMapping("upload")
    @ResponseBody
    public ResponseResult upload(@RequestParam("file") MultipartFile  file){
        return   templateService.upload(file);
    }


    // 模板下载  uuid
    @GetMapping("down")
    public void downLoadTemplate(String fileName, HttpServletResponse response){

        // 1. 在磁盘中查找需要下载的文件
        File file = new File("D:\\upload\\" + fileName);
        try {
            // 将文件读取成输入流
            FileInputStream fileInputStream = new FileInputStream(file);

            // 设置文件的响应格式  以附件的形式进行打开  下载
            response.setContentType("application/force-download");
            // 设置文件下载后的文件名
            response.setHeader("Content-Disposition","attachment;filename="+fileName);
            // 获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            // 流的拷贝
            IOUtils.copy(fileInputStream,outputStream);

            fileInputStream.close();
            outputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
